import axios from 'axios';

import store from '@/store/index'
import {Message, Loading} from 'element-ui'


// 环境的切换
if (process.env.NODE_ENV == 'development') {
    axios.defaults.baseURL = '/lapi';
} else if (process.env.NODE_ENV == 'debug') {
    axios.defaults.baseURL = '/lapi';
} else if (process.env.NODE_ENV == 'production') {
    axios.defaults.baseURL = '/lapi';
}

axios.defaults.timeout = 10000;

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';


//请求拦截

axios.interceptors.request.use(
    config => {
        // 每次发送请求之前判断vuex中是否存在token
        // 如果存在，则统一在http请求的header都加上token，这样后台根据token判断你的登录情况
        // 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断
        const token = store.state.token;
        token && (config.headers.Authorization = token);
        return config;
    },
    error => {
        return Promise.error(error);
    })

axios.interceptors.response.use(
    response => {
        return response
    }, error => {
        Message({
            message: error,
            type: 'error',
            duration: 3 * 1000
        })
        return Promise.reject(error)
    })


export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(res => {
                resolve(res);
            })

    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url,params)
            .then(res => {
                resolve(res);
            })

    });
}


export default axios;

